package com.ruoyi.web.controller.warehouseManagement;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.StoreSettings;
import com.ruoyi.system.domain.Warehouse;
import com.ruoyi.system.domain.vo.WarehouseVO;
import com.ruoyi.system.service.IStoreSettingsService;
import com.ruoyi.system.service.IWarehouseService;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.BaseResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 仓库 Controller
 *
 * @author ruoyi
 * @date 2025-06-02
 */
@Api(tags = "门店仓储设置-门店仓库设置")
@RestController
@RequestMapping("/warehouse")
public class WarehouseController extends BaseController {
    @Autowired
    private IWarehouseService warehouseService;

    @Autowired
    private IStoreSettingsService storeSettingsService;

    @PostMapping("/saveOrUpdate")
    @ApiOperation("新增仓库")
    public BaseResponse<Boolean> save(Warehouse warehouse) {
        if (AbdulEmptyUtils.isEmpty(warehouse.getStoreId())) {
            throw new RuntimeException("请选择增加仓库的门店");
        }
        if (AbdulEmptyUtils.isEmpty(warehouse.getWarehouseName())) {
            throw new RuntimeException("请输入仓库名称");
        }
        if (AbdulEmptyUtils.isEmpty(warehouse.getWarehouseAddress())) {
            throw new RuntimeException("请输入仓库地址");
        }
        if (AbdulEmptyUtils.isEmpty(warehouse.getDetailedAddress())) {
            throw new RuntimeException("请输入仓库详细地址");
        }
        if (AbdulEmptyUtils.isEmpty(warehouse.getContactPerson())) {
            throw new RuntimeException("请输入联系人");
        }
        if (AbdulEmptyUtils.isEmpty(warehouse.getContactPhone())) {
            throw new RuntimeException("请输入联系电话");
        }
        boolean result = warehouseService.saveOrUpdate(warehouse);
        return BaseResponse.success(result);
    }

    /**
     * 仓库列表
     */
    @PostMapping("/page")
    @ApiOperation("仓库列表")
    public BaseResponse<IPage<Warehouse>> page(@RequestBody Warehouse warehouse) {
        if (AbdulEmptyUtils.isEmpty(warehouse.getStoreId())) {
            throw new RuntimeException("请选择门店");
        }
        LambdaQueryWrapper<Warehouse> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Warehouse::getStoreId, warehouse.getStoreId());
        IPage<Warehouse> page = warehouseService.page(new Page<>(warehouse.getPageNum(), warehouse.getPageSize()), wrapper);
        return BaseResponse.success(page);
    }

    /**
     * 门店仓库管理列表
     */
    @ApiOperation("门店仓库管理列表")
    @GetMapping("/list")
    public BaseResponse<IPage<WarehouseVO>> list(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        // 查询所有门店配置（不分页）
        LambdaQueryWrapper<StoreSettings> wrapper = Wrappers.lambdaQuery();
        List<StoreSettings> settingsList = storeSettingsService.list(wrapper);

        // 如果没有数据，直接返回空分页
        if (AbdulEmptyUtils.isEmpty(settingsList)) {
            IPage<WarehouseVO> emptyPage = new Page<>(pageNum, pageSize, 0, true);
            return BaseResponse.success(emptyPage);
        }

        // 构建 VO 列表
        List<WarehouseVO> voList = new ArrayList<>();
        for (StoreSettings record : settingsList) {
            WarehouseVO warehouseVO = new WarehouseVO();
            warehouseVO.setStoreName(record.getStoreName());
            warehouseVO.setStoreCode(record.getStoreId());
            voList.add(warehouseVO);
        }

        // 获取所有仓库信息用于填充默认仓库和数量
        List<Warehouse> warehouseList = warehouseService.list();
        Map<Long, String> defaultWarehouseMap = new java.util.HashMap<>();
        if (!AbdulEmptyUtils.isEmpty(warehouseList)) {
            // 构建 storeId -> 默认仓库名映射
            defaultWarehouseMap = warehouseList.stream()
                    .filter(w -> w.getIsDefault() != null && w.getIsDefault().equals(1))
                    .collect(Collectors.toMap(
                            Warehouse::getStoreId,
                            Warehouse::getWarehouseName,
                            (existing, replacement) -> existing)); // 冲突时保留第一个

            // 构建 storeId -> 仓库数量映射
            Map<Long, Long> storeWarehouseCountMap = warehouseList.stream()
                    .collect(Collectors.groupingBy(Warehouse::getStoreId, Collectors.counting()));

            // 填充默认仓库和数量
            for (WarehouseVO vo : voList) {
                Long storeCode = vo.getStoreCode();
                vo.setDefaultWarehouse(defaultWarehouseMap.get(storeCode));
                vo.setWarehouseCount(storeWarehouseCountMap.getOrDefault(storeCode, 0L));
            }
        }
        // 手动进行分页处理
        int total = voList.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        List<WarehouseVO> paginatedList = voList.subList(fromIndex, toIndex);

        // 创建分页对象并设置数据
        Page<WarehouseVO> page = new Page<>(pageNum, pageSize, total, true);
        page.setRecords(paginatedList);
        return BaseResponse.success(page);
    }
}
